package com.yuns.web.controller.system;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.yuns.aspect.SyslogAnno;
import com.yuns.jwt.JWTToken;
import com.yuns.jwt.JWTUtil;
import com.yuns.model.entity.OperationLog;
import com.yuns.model.entity.SysPermission;
import com.yuns.model.entity.SysUser;
import com.yuns.model.service.OperationLogService;
import com.yuns.model.service.SysPermissionService;
import com.yuns.model.service.SysUserService;
import com.yuns.util.*;
import com.yuns.web.sys.param.LoginBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author luwenchao
 * @since 2018-07-26
 */
@Api(tags = "#系统用户(luwenchao)- Controller")
@Slf4j
@RestController
@RequestMapping("/sysLogin")
public class SysLoginController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysPermissionService isys_permissionService;
    @Autowired
    private OperationLogService iOperationLogService;





    @ApiOperation(value = "用户登录|已完成")
    @PostMapping(value = "login")
    @SyslogAnno("登录")
    public ResultJson isLogin(@RequestBody LoginBean loginBean, HttpServletRequest request) {

        String token = JWTUtil.sign(loginBean.getUserName(), loginBean.getUserPwd());
        Map<Object, Object> map = new HashMap<>();
        JWTToken jwtToken = new JWTToken(token);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(jwtToken);
        } catch (UnknownAccountException e) {
            return ResultJson.error("未知账户/没找到帐号,登录失败！");
        } catch (UnsupportedTokenException e) {
            return ResultJson.error("身份令牌异常！");
        }
        log.info("login end ! .......................................");
        SysUser user = sysUserService.selectOne(new EntityWrapper<SysUser>().eq("account", loginBean.getUserName()));

        user.setPassword(null);
        if (user.getType().equals(0)) {
            List<SysPermission> tree = isys_permissionService.findTree(0);
            user.setPermissions(tree);
        }

        OperationLog operationLog =new OperationLog();
        operationLog.setType("1");
        operationLog.setOperationModel("登录");
        operationLog.setCreateBy(user.getUserName());
        operationLog.setOperationValue(user.getUserName()+"使用账号"+user.getAccount()+"进行登录");
        operationLog.setCreateTime(new Date());
        iOperationLogService.insert(operationLog);
        Date date = new Date(System.currentTimeMillis() + JWTUtil.EXPIRE_TIME);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("data", user);
        map.put("token", token);
        map.put("expiresTime", simpleDateFormat.format(date));
        request.getSession().setAttribute("token", token);
        log.info("login end ! .......................................");
        return ResultJson.ok(map);

    }


    @ApiOperation(value = "第三方接入用户登录|已完成")
    @PostMapping(value = "sysTb/login")
    public ResultJson sysTbLogin(@RequestBody LoginBean loginBean, HttpServletRequest request) {

        String token = JWTUtil.sign(loginBean.getUserName(), loginBean.getUserPwd());
        Map<Object, Object> map = new HashMap<>();
        JWTToken jwtToken = new JWTToken(token);
        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(jwtToken);
        } catch (UnknownAccountException e) {
            return ResultJson.error("未知账户/没找到帐号,登录失败！");
        } catch (UnsupportedTokenException e) {
            return ResultJson.error("身份令牌异常！");
        }

        log.info("login end ! .......................................");
        SysUser user = sysUserService.selectOne(new EntityWrapper<SysUser>().eq("account", loginBean.getUserName()));
        user.setPassword(null);
        if (user.getType().equals(0)) {
            List<SysPermission> tree = isys_permissionService.findTree(0);
            user.setPermissions(tree);
        }
        Date date = new Date(System.currentTimeMillis() + JWTUtil.EXPIRE_TIME);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        map.put("data", com.yuns.user);
        map.put("token", token);
        map.put("expiresTime", simpleDateFormat.format(date));
        request.getSession().setAttribute("token", token);
        log.info("login end ! .......................................");
        return ResultJson.ok(map);
    }

    @ApiOperation(value = "密码重置|已完成")
    @PostMapping(value = "resetPassword/{newPassWord}")
    @SyslogAnno("修改密码")
    public ResultJson resetPassword( @ApiParam(value = "新密码", required = true) @PathVariable(name = "newPassWord", required = false) String newPassWord) {
        Assert.hasLength(newPassWord, "密码不能为空！");
        SysUser user1 = JWTUtil.getUser();
        SysUser user = sysUserService.selectOne(new EntityWrapper<SysUser>().eq("account", user1.getAccount()));
        if (user == null) {
            return ResultJson.error("用户不存在");
        }
        OperationLog operationLog =new OperationLog();
        operationLog.setType("1");
        operationLog.setOperationModel("修改密码");
        operationLog.setCreateBy(user.getUserName());
        operationLog.setOperationValue("系统用户"+user.getUserName()+"修改密码");
        operationLog.setCreateTime(new Date());
        iOperationLogService.insert(operationLog);
        user.setPassword(newPassWord);
        sysUserService.updateById(user);
        return ResultJson.ok(user, "修改密码成功，请重新登录！");
    }

}

